#include<iostream>
#include<string>
#include<vector>
#include<set>
#include<algorithm>
using namespace std;



//  Definition for singly-linked list.
  struct ListNode {
      int val;
      ListNode *next;
      ListNode(int x) : val(x), next(NULL) {}
  };
 
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        set<ListNode*> S;
        ListNode* curr1 = headA;
        while(curr1!=nullptr){
            S.insert(curr1);
            curr1 = curr1->next;
        }
        ListNode* curr2 = headB;
        while(curr2!=nullptr){
            if(S.insert(curr2).second==false){
                return curr2;
            }
            curr2 = curr2->next;
        }
        return nullptr;

        
    }
};

